package com.leyou.auth.interceptors;

import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.auth.utils.UserContext;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.common.utils.JwtConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器  判断是否登录
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {


    private JwtUtils jwtUtils;

    public LoginInterceptor(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取cookie中的jwt
        String jwt = CookieUtils.getCookieValue(request, JwtConstants.COOKIE_NAME);
        if (StringUtils.isBlank(jwt)){
            throw  new LyException(401,"未登录，请先登录！");
        }
        //验证jwt 获取用户信息
        Payload payload = jwtUtils.parseJwt(jwt);
        UserDetails userDetail = payload.getUserDetail();
        // 判断结果，如果正确则放行
        if (userDetail == null){
            throw  new LyException(401,"未登录，请先登录！");
        }

        // 保存用户
        UserContext.setUser(userDetail);
        UserContext.setJwt(jwt);

        //放行
        log.info("用户{}正在访问！",userDetail.getUsername());


        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 业务结束后，移除用户
        UserContext.removeUser();
        // 业务结束后，移除jwt
        UserContext.removeJwt();
    }
}
